<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"iyue.top","root":"/","images":"/images","scheme":"Muse","version":"8.3.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>
<meta name="description" content="问题引出由于django本身的权限管理是基于cookie来认证的，而整个过程并不需要前端做什么，直接后端完成；但跨域的时候，产生几个问题；  django如何跨域？ django跨域后可以正常的写入cookie吗？  其实，跨域实现的方法有很多种，可以查看前端常见跨域解决方案（全），在此我们使用cors跨域的方式 cors跨域概述浏览器将CORS请求分成两类：简单请求（simple request">
<meta property="og:type" content="article">
<meta property="og:title" content="django的跨域请求设置">
<meta property="og:url" content="http://iyue.top/2018/09/06/django%E7%9A%84%E8%B7%A8%E5%9F%9F%E8%AF%B7%E6%B1%82%E8%AE%BE%E7%BD%AE/index.html">
<meta property="og:site_name" content="山外小楼">
<meta property="og:description" content="问题引出由于django本身的权限管理是基于cookie来认证的，而整个过程并不需要前端做什么，直接后端完成；但跨域的时候，产生几个问题；  django如何跨域？ django跨域后可以正常的写入cookie吗？  其实，跨域实现的方法有很多种，可以查看前端常见跨域解决方案（全），在此我们使用cors跨域的方式 cors跨域概述浏览器将CORS请求分成两类：简单请求（simple request">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-09-06T03:26:30.000Z">
<meta property="article:modified_time" content="2021-04-27T08:41:57.636Z">
<meta property="article:author" content="萌新">
<meta property="article:tag" content="django">
<meta property="article:tag" content="跨域">
<meta property="article:tag" content="cookie">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://iyue.top/2018/09/06/django%E7%9A%84%E8%B7%A8%E5%9F%9F%E8%AF%B7%E6%B1%82%E8%AE%BE%E7%BD%AE/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>django的跨域请求设置 | 山外小楼</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">山外小楼</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">前端攻略</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%97%AE%E9%A2%98%E5%BC%95%E5%87%BA"><span class="nav-number">1.</span> <span class="nav-text">问题引出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#cors%E8%B7%A8%E5%9F%9F%E6%A6%82%E8%BF%B0"><span class="nav-number">2.</span> <span class="nav-text">cors跨域概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#django%E8%B7%A8%E5%9F%9F%E8%AE%BE%E7%BD%AE"><span class="nav-number">3.</span> <span class="nav-text">django跨域设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%98%BE%E5%BC%8F%E8%AE%BE%E7%BD%AEcookie"><span class="nav-number">4.</span> <span class="nav-text">显式设置cookie</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E7%AB%AF%E8%AE%BE%E7%BD%AE"><span class="nav-number">5.</span> <span class="nav-text">前端设置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AA%81%E7%84%B6%E6%9D%A5%E7%9A%84%E7%96%91%E9%97%AE"><span class="nav-number">6.</span> <span class="nav-text">突然来的疑问</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%A7%A3%E7%AD%94%E7%96%91%E9%97%AE"><span class="nav-number">7.</span> <span class="nav-text">解答疑问</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B7%A8%E5%9F%9F%E5%86%99%E6%9C%AC%E5%9F%9Fcookie"><span class="nav-number">8.</span> <span class="nav-text">跨域写本域cookie</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">萌新</p>
  <div class="site-description" itemprop="description">我是萌新</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">21</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://iyue.top/2018/09/06/django%E7%9A%84%E8%B7%A8%E5%9F%9F%E8%AF%B7%E6%B1%82%E8%AE%BE%E7%BD%AE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="萌新">
      <meta itemprop="description" content="我是萌新">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="山外小楼">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          django的跨域请求设置
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2018-09-06 11:26:30" itemprop="dateCreated datePublished" datetime="2018-09-06T11:26:30+08:00">2018-09-06</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-04-27 16:41:57" itemprop="dateModified" datetime="2021-04-27T16:41:57+08:00">2021-04-27</time>
      </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="问题引出"><a href="#问题引出" class="headerlink" title="问题引出"></a>问题引出</h2><p>由于django本身的权限管理是基于cookie来认证的，而整个过程并不需要前端做什么，直接后端完成；但跨域的时候，产生几个问题；</p>
<ol>
<li>django如何跨域？</li>
<li>django跨域后可以正常的写入cookie吗？</li>
</ol>
<p>其实，跨域实现的方法有很多种，可以查看<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000011145364">前端常见跨域解决方案（全）</a>，在此我们使用cors跨域的方式</p>
<h2 id="cors跨域概述"><a href="#cors跨域概述" class="headerlink" title="cors跨域概述"></a>cors跨域概述</h2><p>浏览器将CORS请求分成两类：简单请求（simple request）和非简单请求（not-so-simple request）  </p>
<p>相关内容可以参考<a target="_blank" rel="noopener" href="https://www.cnblogs.com/keyi/p/6726089.html">跨域CORS原理及调用具体示例</a></p>
<blockquote>
<p>引起我们注意的一点就是同为post请求，当<code>Content-Type</code>的值为<code>application/json</code>时，就变成了非简单请求，基础表现就是浏览器会先发一个”预检”请求</p>
</blockquote>
<h2 id="django跨域设置"><a href="#django跨域设置" class="headerlink" title="django跨域设置"></a>django跨域设置</h2><ol>
<li>执行安装</li>
</ol>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># https://github.com/ottoyiu/django-cors-headers/</span></span><br><span class="line">pip install django-cors-headers</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>配置settings.py</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS = (</span><br><span class="line">    ...</span><br><span class="line">    <span class="string">&#x27;corsheaders&#x27;</span>,</span><br><span class="line">    ...</span><br><span class="line">)</span><br><span class="line">...</span><br><span class="line">MIDDLEWARE = [  <span class="comment"># Or MIDDLEWARE_CLASSES on Django &lt; 1.10</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="string">&#x27;corsheaders.middleware.CorsMiddleware&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;django.middleware.common.CommonMiddleware&#x27;</span>,</span><br><span class="line">    ...</span><br><span class="line">]</span><br><span class="line">...</span><br><span class="line"><span class="comment"># cookies will be allowed to be included in cross-site HTTP requests</span></span><br><span class="line">CORS_ALLOW_CREDENTIALS = <span class="literal">True</span> </span><br><span class="line"><span class="comment"># If True, the whitelist will not be used and all origins will be accepted</span></span><br><span class="line">CORS_ORIGIN_ALLOW_ALL = <span class="literal">False</span></span><br><span class="line"><span class="comment"># A list of origin hostnames that are authorized to make cross-site HTTP requests</span></span><br><span class="line">CORS_ORIGIN_WHITELIST = (</span><br><span class="line">    <span class="string">&#x27;localhost:8888&#x27;</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<h2 id="显式设置cookie"><a href="#显式设置cookie" class="headerlink" title="显式设置cookie"></a>显式设置cookie</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># view.py</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span>(<span class="params">request</span>):</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">&#x27;POST&#x27;</span>:</span><br><span class="line">        data = &#123;</span><br><span class="line">            <span class="string">&#x27;code&#x27;</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="string">&#x27;msg&#x27;</span>: <span class="string">&#x27;this is a test&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;data&#x27;</span>: <span class="string">&#x27;POST&#x27;</span></span><br><span class="line">        &#125;</span><br><span class="line">        rep = HttpResponse(json.dumps(data, cls=CJsonEncoder), content_type=<span class="string">&quot;application/json&quot;</span>)</span><br><span class="line">        rep.set_cookie(<span class="string">&#x27;key&#x27;</span>, <span class="string">&#x27;value&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> rep</span><br></pre></td></tr></table></figure>

<h2 id="前端设置"><a href="#前端设置" class="headerlink" title="前端设置"></a>前端设置</h2><p>前端默认不允许跨域携带cookies，需进行显式的设置；不同的库可能有一些细微的差别；</p>
<blockquote>
<p>需要注意的是，以原生表单的形式，发起post请求，是可以携带cookie自动跨域的，无需其他设置；form表单可以跨域一个是历史原因要保持兼容性，一个是form表单会刷新页面不会把结果返回给js，所以相对安全，但其实请求已经发送出去了，你只是拿不到响应而已；这个问题会引起CSRF攻击；</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 原生js（亲测可用，其余未作测试）</span></span><br><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();  </span><br><span class="line">xhr.open(<span class="string">&quot;POST&quot;</span>, <span class="string">&quot;http://localhost:8000/api/test/&quot;</span>, <span class="literal">true</span>);  </span><br><span class="line">xhr.withCredentials = <span class="literal">true</span>; <span class="comment">//支持跨域发送cookies</span></span><br><span class="line">xhr.send();</span><br><span class="line"></span><br><span class="line"><span class="comment">// jQuery</span></span><br><span class="line">$.ajax(&#123;</span><br><span class="line">    type: <span class="string">&quot;POST&quot;</span>,</span><br><span class="line">    url: <span class="string">&quot;http://localhost:8000/api/test/&quot;</span>,</span><br><span class="line">    dataType: <span class="string">&#x27;jsonp&#x27;</span>,</span><br><span class="line">    xhrFields: &#123;<span class="attr">withCredentials</span>: <span class="literal">true</span>&#125;,</span><br><span class="line">    crossDomain: <span class="literal">true</span>,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// axios（vue常用的方案）</span></span><br><span class="line">axios.create(&#123;</span><br><span class="line">  timeout: <span class="number">5000</span>,</span><br><span class="line">  withCredentials: <span class="literal">true</span> <span class="comment">// 允许携带cookie</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="突然来的疑问"><a href="#突然来的疑问" class="headerlink" title="突然来的疑问"></a>突然来的疑问</h2><p>写到此时，我所作的测试都是在本地测的，服务器端在localhost:8000,前端在localhost:8888;而跨域操作所写的cookie均在localhost之下，这样就有一个问题，跨域读写的cookie到底是哪里？是发起请求页的域还是请求地址的域？</p>
<h2 id="解答疑问"><a href="#解答疑问" class="headerlink" title="解答疑问"></a>解答疑问</h2><p>我们得到的答案是cors跨域读写的cookie都是请求地址的cookie；比如我们请求第三方cdn，并不会携带本站的cookie，发送跨域请求也一样，只会携带请求指向地址的域的cookie。（这也是跨站伪造请求csrf的原理）  </p>
<blockquote>
<p>服务器如果要发送Cookie，Access-Control-Allow-Origin就不能设为星号，必须指定明确的、与请求网页一致的域名。同时，Cookie依然遵循同源政策，只有用服务器域名设置的Cookie才会上传，其他域名的Cookie并不会上传，且（跨源）原网页代码中的document.cookie也无法读取服务器域名下的Cookie。</p>
</blockquote>
<p>如果非要跨域写cookie呢？有什么办法吗？</p>
<h2 id="跨域写本域cookie"><a href="#跨域写本域cookie" class="headerlink" title="跨域写本域cookie"></a>跨域写本域cookie</h2><p>查到的方法如下：<br>可以通过ngix反向代理跨域配置：proxy_cookie_domain b.com a.com;<br>也可以通过中间件http-proxy-middleware代理跨域时，配置加上cookieDomainRewrite: ‘a.com’参数，都是用来修改转发过来的cookie中域名为当前a.com域，所以实现了a.com下cookie写入。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/django/" rel="tag"># django</a>
              <a href="/tags/%E8%B7%A8%E5%9F%9F/" rel="tag"># 跨域</a>
              <a href="/tags/cookie/" rel="tag"># cookie</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/09/05/post%E8%AF%B7%E6%B1%82%E7%9A%84%E6%8F%90%E4%BA%A4%E6%95%B0%E6%8D%AE%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/" rel="prev" title="post请求的提交数据的几种方式">
                  <i class="fa fa-chevron-left"></i> post请求的提交数据的几种方式
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/09/06/%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F/" rel="next" title="单点登录的实现方式">
                  单点登录的实现方式 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">萌新</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  






  





</body>
</html>
